//
//  PhotographViewController.m
//  miniStore
//
//  Created by liliang on 13-7-10.
//  Copyright (c) 2013年 李 良. All rights reserved.
//

#import "MainViewController.h"
#import "toolbox.h"
#import "ListViewController.h"

#import "BDKNotifyHUD.h"
@interface MainViewController ()<UITextFieldDelegate,UITextViewDelegate,UIPopoverControllerDelegate>
{
    int widgetY;
}
@property(nonatomic,strong) NSMutableArray *mainArray;
@property(nonatomic,strong) UIPopoverController *popover;
@property(nonatomic,strong) NSMutableDictionary *informationDictionary;
@property(nonatomic,strong) NSString *filePath;
@property(nonatomic,strong) NSString *informationPath;
@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.informationPath=@"information".docPath;
    [self.informationPath createDir];
    self.informationDictionary = [NSMutableDictionary dictionary];
    [self.view sendSubviewToBack:self.subview];
    NSString *file = self.filePath;
    self.mainArray = file.read.jsonObject;
    [self setUpViews];

    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}


-(MainViewController *)initWith:(NSString *)filePath
{
    self = [super init];
    if (self) {
        self.filePath = filePath;
    }
    return self;
}

-(void)setUpViews
{
    UIFont *font=[UIFont systemFontOfSize:20];
    [self.subview removeAllSubviews];
    for (int i = 0; i < self.mainArray.count; i++) {
        NSDictionary *currentItem = self.mainArray[i];
        int width = [currentItem[@"width"] integerValue];
        int height = [currentItem[@"height"] integerValue];
        int x = [currentItem[@"x"] integerValue];
        int y = [currentItem[@"y"] integerValue];
        CGRect rect = CGRectMake(x, y, width, height);
        NSDictionary *properties = currentItem[@"properties"];
        NSString *type = currentItem[@"type"];
        NSString *name = currentItem[@"name"];

        if ([type isEqualToString:@"label"]) {
            UILabel *label = [[UILabel alloc] initWithFrame:rect];
            label.text = name;
            label.font = font;
            label.lineBreakMode=NSLineBreakByWordWrapping;
            label.numberOfLines=0;
            [self.subview addSubview:label];
            label.userInfo=currentItem;
        }

        if ([type isEqualToString:@"button"]) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = rect;
            button.titleLabel.font = font;
            NSString *action = currentItem[@"action"];
            SEL selector=NSSelectorFromString(action);
            [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
            [self.subview addSubview:button];
            button.adjustsImageWhenHighlighted = NO;  //隐藏点击时的效果
            button.userInfo=currentItem;
        }
        
        if ([type isEqualToString:@"camera"]) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = rect;
            button.imageView.contentMode = UIViewContentModeScaleAspectFill;
            
            button.titleLabel.font = font;
            NSString *action = currentItem[@"action"];
            SEL selector=NSSelectorFromString(action);
            [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
            [self.subview addSubview:button];
            button.adjustsImageWhenHighlighted = NO;  //隐藏点击时的效果
            button.userInfo=currentItem;
        }

        if ([type isEqualToString:@"textview"]) {
            UITextView *textview = [[UITextView alloc] initWithFrame:rect];
            textview.font = font;
            textview.delegate = self;
            textview.autocapitalizationType = UITextAutocapitalizationTypeNone;
            textview.autocorrectionType = UITextAutocorrectionTypeNo;   //限定输入时的大小写问题
            [self.subview addSubview:textview];
            NSString *keyboard = properties[@"keyboard"];
            if ([keyboard isEqualToString:@"number"]) {
                textview.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            }
            textview.userInfo = currentItem;
        }

        if ([type isEqualToString:@"textfield"]) {
            UITextField *textfield = [[UITextField alloc] initWithFrame:rect];
            textfield.font = font;
            textfield.delegate = self;
            textfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
            textfield.autocorrectionType = UITextAutocorrectionTypeNo;   //限定输入时的大小写问题
            [self.subview addSubview:textfield];
            textfield.userInfo = currentItem;
            NSString *placeholder = properties[@"placeholder"];
            if (placeholder != nil) {
                textfield.placeholder = placeholder;
            }
            NSString *keyboard = properties[@"keyboard"];
            if ([keyboard isEqualToString:@"number"]) {
                textfield.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            }
            if ([keyboard isEqualToString:@"email"]) {
                textfield.keyboardType = UIKeyboardTypeEmailAddress;
            }
        }


        if ([type isEqualToString:@"image"]) {
            UIImageView *imageview = [[UIImageView alloc] initWithFrame:rect];
            NSString *imagePath=name.docPath;
            imageview.image=[UIImage imageWithContentsOfFile:imagePath];
            [self.subview addSubview:imageview];
            imageview.userInfo=currentItem;
        }

        if ([type isEqualToString:@"list"]) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = rect;
            [button addTarget:self action:@selector(listSelect:) forControlEvents:UIControlEventTouchUpInside];
            [self.subview addSubview:button];
            button.userInfo=currentItem;
            NSString *key = currentItem[@"name"];
            NSDictionary *dic = properties[@"default"];
            NSString *description = dic[@"description"];
            if (description != nil) {
                [button setTitle:description forState:UIControlStateNormal];
                [self.informationDictionary setValue:description forKey:key];
            }
            button.titleLabel.textAlignment = NSTextAlignmentLeft;
        }
    }

    [self refreshView];
}

-(void)refreshView
{
    for (UIView *view in self.subview.subviews) {
        if (view.isFirstResponder) {
            [view resignFirstResponder];
        }

        NSDictionary *currentItem = view.userInfo;
        NSString *type = currentItem[@"type"];
        NSString *name = currentItem[@"name"];

        if ([type isEqualToString:@"button"]) {

        }

        if ([type isEqualToString:@"camera"]) {
            UIButton *button = (id)view;
            UIImage *value = self.informationDictionary[name];
            [button setImage:value forState:UIControlStateNormal];
        }

        if ([type isEqualToString:@"textview"]) {
            UITextView *textview = (id)view;
            NSString *value=self.informationDictionary[name];
            textview.text=value;
        }

        if ([type isEqualToString:@"textfield"]) {
            UITextField *textfield = (id)view;
            NSString *value=self.informationDictionary[name];
            textfield.text=value;
           
        }

        if ([type isEqualToString:@"list"]) {
            UIButton *button=(id)view;
            NSString *value=self.informationDictionary[name];
            [button  setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [button setTitle:value forState:UIControlStateNormal];
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)onBackClick
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)submit
{
    BOOL isRequire = NO;
    NSArray *subviews = self.subview.subviews;
    for (UIView *view in subviews) {
        NSDictionary *currentItem = view.userInfo;
        NSDictionary *properties = currentItem[@"properties"];
        NSString *name = currentItem[@"name"];
        NSNumber *require = properties[@"require"];
        NSString *formation = properties[@"formation"];
        NSString *value = self.informationDictionary[name];

        if (require.boolValue) {
            if (value == nil) {
                isRequire = YES;
            }
            else
            {
                if ([formation isEqualToString:@"email"]) {
                    if(![self isValidateEmail:value]){
                        [self notifyWithMessage:LOC_STR(@"邮箱填写有误")];
                        return;
                    }
                }
                if ([formation isEqualToString:@"phone"]) {
                    if (![self isValidateMobile:value]) {
                        [self notifyWithMessage:LOC_STR(@"电话填写有误")];
                        return;
                    }
                }

            }

        }
        else
        {
            if ([formation isEqualToString:@"email"]) {
                if(![self isValidateEmail:value]){
                    [self notifyWithMessage:LOC_STR(@"邮箱填写有误")];
                    return;
                }
            }
            if ([formation isEqualToString:@"phone"]) {
                if (![self isValidateMobile:value]) {
                    [self notifyWithMessage:LOC_STR(@"电话填写有误")];
                    return;
                }
            }

        }
        
    }
    if (isRequire) {
        NSString *message = LOC_STR(@"您是否有漏填?请仔细检查.");
        [self notifyWithMessage:message];
    }
    else
    {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (NSString *key in self.informationDictionary) {
            id value = self.informationDictionary[key];
            if ([value isKindOfClass:[UIImage class]]) {
                NSData *data = UIImageJPEGRepresentation(value, 0.2);
                [dic setValue:data.hexString forKey:key];
            }
        }

        for (NSString *key in dic) {
            NSString *value = dic[key];
            [self.informationDictionary setValue:value forKey:key];
        }
        AppController *app = [AppController shared];
        NSString *uid=uniqueID();
        [self.informationDictionary setValue:uid forKey:@"uid"];
        NSDate *date=[NSDate date];
        [self.informationDictionary setValue:date.description forKey:@"time"];
        NSString *store = app.config[@"store"];
        [self.informationDictionary setValue:store forKey:@"store"];
        NSString *local=[self.informationPath stringByAppendingPathComponent:uid];
        [self dictionaryConvert];
        [local write:self.informationDictionary.jsonData];

        static dispatch_queue_t uploadQueue;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            uploadQueue = dispatch_queue_create("upload", 0);
        });

        dispatch_async(uploadQueue, ^{
            AppController *app = [AppController shared];
            NSMutableArray *files =[app getAllFiles:[@"information".docPath listDir]];
            for(NSString *filename in files)
            {
                [app uploadFiles:filename];

            }
        });

        [self.navigationController popToRootViewControllerAnimated:YES];
        [self.informationDictionary removeAllObjects];
        [self refreshView];

    }
}

//提醒框
-(void)notifyWithMessage:(NSString *)message
{
    BDKNotifyHUD *hud = [BDKNotifyHUD notifyHUDWithImage:nil text:message];
    hud.center = CGPointMake(self.view.center.x, self.view.center.y);
    if (hud.isAnimating)
        return;

    [self.view addSubview:hud];
    [hud presentWithDuration:1.0f speed:0.5f inView:self.view completion:^{
        [hud removeFromSuperview];
    }];
    
}

/*邮箱验证*/
-(BOOL)isValidateEmail:(NSString *)email
{

    BOOL isValid = YES;
    if (email.length > 0) {
        if (![email contains:@"@"]) {
            isValid = NO;
        }
        else
        {
            NSRange range = [email rangeOfString:@"@"];
            NSString *local = [email substringToIndex:range.location];
            NSString *domain = [email substringFromIndex:range.location + 1];
            if (local.length > 64 || local.length < 1) {
                isValid = NO;
            }
            else if (domain.length > 255 || domain.length < 1) {
                isValid = NO;
            }
            else if ([[local substringToIndex:1] isEqualToString: @"."] || [[local substringFromIndex:local.length - 1] isEqualToString:@"."]) {
                isValid = NO;
            }
            else if ([local contains:@".."]) {
                isValid = NO;
            }
            else if ([domain contains:@".."]) {
                isValid = NO;
            }
            else  {
                NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
                NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
                isValid = [emailTest evaluateWithObject:email];
            }
        }
    }
    return isValid;
}

/*手机号码验证*/
-(BOOL) isValidateMobile:(NSString *)mobile
{
    NSString *phoneRegex = @"^\\d+$";//所有数字,个数大于等于1
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

//统一中英文的不同回答  对提交的答案进行处理
-(void)dictionaryConvert
{
    for (NSDictionary *dic in self.mainArray)
    {
        NSString *key = dic[@"name"];
        NSDictionary *properties = dic[@"properties"];
        NSString *value = self.informationDictionary[key];
        NSArray *options = properties[@"options"];
        if (options.count)
        {
            for (NSDictionary *option in options)
            {
                NSString *name = option[@"description"];
                if (name != nil) {
                    if ([value isEqualToString:name])
                    {
                        NSString *val = option[@"value"];
                        [self.informationDictionary setValue:val forKey:key];
                    }
                }

            }
        }
        
    }

    for (NSDictionary *dic in self.mainArray) {
        NSString *key = dic[@"name"];
        NSDictionary *properties = dic[@"properties"];
        NSString *exist = properties[@"exist"];
        if (exist != nil) {
            NSArray *keys = self.informationDictionary.allKeys;
            if(![keys containsObject:exist])
            {
                [self.informationDictionary removeObjectForKey:key];
            }
        }

    }
    
}

//列表
-(void)listSelect:(UIButton*)sender
{
    [self clickToHidetheKeyboard];
    NSMutableDictionary *currentItem=sender.userInfo;
    ListViewController *list = [[ListViewController alloc] initWithlistDictionary:currentItem];
    list.delegate = self;
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:list];
    popover.delegate = self;
    if (sender.frame.origin.y > 500) {
        [popover presentPopoverFromRect:sender.frame inView:self.subview permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
    }
    else
    {
        [popover presentPopoverFromRect:sender.frame inView:self.subview permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    }
    self.popover = popover;
    
}

-(void)ListController:(ListViewController*)controller didSelectedItemAtIndex:(int)index withInfo:(id)info
{
    NSString *key = info[@"name"];
    NSDictionary *properties = info[@"properties"];
    NSArray *options = properties[@"options"];
    NSDictionary *current = options[index];
    NSString *description = current[@"description"];
    if (description != nil) {
        [self.informationDictionary setValue:description forKey:key];
    }
    [self.popover dismissPopoverAnimated:YES];
    [self refreshView];
}


-(void)openCamera:(UIButton *)sender{
    [self clickToHidetheKeyboard];
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"拍摄",@"选取照片", nil];
    sheet.userInfo = sender;
    [sheet showFromRect:sender.frame inView:self.subview animated:NO];
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self openPickerWithSource:UIImagePickerControllerSourceTypeCamera AndSender:actionSheet.userInfo];
    }

    if (buttonIndex == 1) {
        [self openPickerWithSource:UIImagePickerControllerSourceTypePhotoLibrary AndSender:actionSheet.userInfo];
    }
}

-(void)openPickerWithSource:(UIImagePickerControllerSourceType)source AndSender:(id)sender
{
    CGRect rect;
    UIView *view = sender;
    rect = view.frame;
    
    UIImagePickerController *picker=[[UIImagePickerController alloc] init];
    picker.delegate=self;
    picker.view.userInfo = sender;
    BOOL pop=NO;
    if (source!=UIImagePickerControllerSourceTypeCamera) {
        picker.sourceType=source;
        if (deviceIsPad()) {
            pop=YES;
            if (pop) {
                UIPopoverController *popover=[[UIPopoverController alloc] initWithContentViewController:picker];
                popover.delegate=self;
                [popover presentPopoverFromRect:rect inView:self.subview permittedArrowDirections:UIPopoverArrowDirectionAny animated:NO];
                self.popover=popover;
            }
        }
    }
    else
    {
        if (!deviceIsSimulator()) {
            picker.sourceType=source;
            [self presentViewController:picker animated:NO completion:nil];
        }
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIView *view = picker.view.userInfo;
    NSDictionary *currentItem = view.userInfo;
    NSString *key = currentItem[@"name"];
    if (self.popover) {
        [self.popover dismissPopoverAnimated:NO];
    }else{
        [picker dismissViewControllerAnimated:NO completion:nil];
    }

    UIImage *image=info[UIImagePickerControllerOriginalImage];
    [self.informationDictionary setValue:image forKey:key];
    [picker dismissViewControllerAnimated:NO completion:nil];
    [self refreshView];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:NO completion:nil];
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController{
    self.popover=nil;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSDictionary *currentItem = textField.userInfo;
    NSString *key = currentItem[@"name"];
    NSString *value = textField.text;
    if (value != nil) {
        [self.informationDictionary setValue:value forKey:key];
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    NSDictionary *currentItem = textView.userInfo;
    NSString *key = currentItem[@"name"];
    NSString *value = textView.text;
    if (value != nil) {
        [self.informationDictionary setValue:value forKey:key];
    }
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    textView.text = @"\n";
    textView.text = @"";
    NSString *value = self.informationDictionary[textView.userInfo[@"name"]];
    textView.text = value;
    widgetY = CGRectGetMaxY(textView.frame);
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    widgetY = CGRectGetMaxY(textField.frame);
    return YES;
}


- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int yHeight = keyboardRect.size.width;

    [UIView animateWithDuration:0.25 animations:^{
        int offset=CGRectGetHeight(self.subview.frame)-widgetY;
        if (offset<yHeight) {
            offset=yHeight-offset;
        }else{
            offset=0;
        }
        self.subview.frame=CGRectOffset(self.subview.frame, 0, -self.subview.frame.origin.y-offset);
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25 animations:^{
        self.subview.frame=CGRectOffset(self.subview.frame, 0, -self.subview.frame.origin.y);
    }];
}
-(void)clickToHidetheKeyboard
{
    NSArray *subviews = self.subview.subviews;
    for (UIView *v in subviews) {
        if ([v isFirstResponder]) {
            [v resignFirstResponder];
        }
    }
}

//任意点击隐藏键盘
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *t = [touches anyObject];
    if(t.view == self.subview)
    {
        for (UIView *v in self.subview.subviews) {
            [v resignFirstResponder];
        }
    }
}

@end
